<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useTheme } from '@/composables/useTheme'
import { getThemeList, getThemesByCategory, themeCategories } from '@/config/themes'
import { motion, AnimatePresence } from 'motion-v'

const { currentTheme, setTheme, isTransitioning } = useTheme()

const allThemes = getThemeList()
const categories = themeCategories

const isOpen = ref(false)
const selectedCategory = ref<string>('all')
const switcherRef = ref<HTMLElement>()
const previewTheme = ref<string | null>(null)

// 过滤后的主题列表
const filteredThemes = computed(() => {
  if (selectedCategory.value === 'all') {
    return allThemes
  }
  return getThemesByCategory(selectedCategory.value)
})

// 当前分类信息
const currentCategoryInfo = computed(() => {
  if (selectedCategory.value === 'all') {
    return { name: '全部主题', icon: '🎨', description: '所有可用的主题' }
  }
  return categories.find((cat) => cat.id === selectedCategory.value) || categories[0]
})

// 切换主题选择器
const toggleSwitcher = () => {
  isOpen.value = !isOpen.value
}

// 打开主题选择器
const openSwitcher = () => {
  isOpen.value = true
}

// 关闭主题选择器
const closeSwitcher = () => {
  isOpen.value = false
}

// 选择分类
const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId
}

// 暴露方法和状态给父组件
defineExpose({
  toggleSwitcher,
  openSwitcher,
  closeSwitcher,
  isOpen,
  currentTheme,
})

// 预览主题
const previewThemeHandler = (themeId: string) => {
  previewTheme.value = themeId
  // 临时应用主题预览
  document.documentElement.setAttribute('data-theme', themeId)
}

// 取消预览
const cancelPreview = () => {
  previewTheme.value = null
  // 恢复当前主题
  document.documentElement.setAttribute('data-theme', currentTheme.value.id)
}

// 应用主题
const applyTheme = async (themeId: string) => {
  if (themeId !== currentTheme.value.id) {
    await setTheme(themeId)
  }
  previewTheme.value = null
  // 不再自动关闭对话框，让用户手动点击确定按钮
}

// 选择主题（不关闭对话框）
const selectTheme = (themeId: string) => {
  previewThemeHandler(themeId)
}

// 关闭对话框
const closeDialog = () => {
  // 如果有预览主题，先取消预览
  if (previewTheme.value) {
    cancelPreview()
  }
  isOpen.value = false
}

// 点击外部关闭
const handleClickOutside = (event: Event) => {
  if (switcherRef.value && !switcherRef.value.contains(event.target as Node)) {
    closeDialog()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
  <div ref="switcherRef" class="relative">
    <!-- 自定义触发器插槽，如果没有提供则使用默认按钮 -->
    <slot
      name="trigger"
      :toggle="toggleSwitcher"
      :open="openSwitcher"
      :close="closeSwitcher"
      :is-open="isOpen"
      :current-theme="currentTheme"
      :is-transitioning="isTransitioning"
    >
      <!-- 默认主题切换按钮 -->
      <button
        @click="toggleSwitcher"
        :disabled="isTransitioning"
        class="theme-toggle-btn btn btn-ghost btn-circle h-9 w-9 min-h-0 sm:h-10 sm:w-10 md:h-12 md:w-12 p-0 relative overflow-hidden group"
        :class="{
          loading: isTransitioning,
          'theme-toggle-btn--active': isOpen,
        }"
        title="切换主题"
      >
        <div
          class="theme-icon w-5 h-5 sm:w-6 sm:h-6 flex items-center justify-center text-base sm:text-lg"
        >
          {{ currentTheme.icon }}
        </div>

        <!-- 加载指示器 -->
        <div
          v-if="isTransitioning"
          class="absolute inset-0 flex items-center justify-center bg-base-100/80 rounded-full"
        >
          <div class="loading loading-spinner loading-xs sm:loading-sm"></div>
        </div>
      </button>
    </slot>

    <!-- 主题选择面板 -->
    <Teleport to="body">
      <AnimatePresence>
        <motion.div
          v-if="isOpen"
          :initial="{ opacity: 0, scale: 0.9, y: -20 }"
          :animate="{ opacity: 1, scale: 1, y: 0 }"
          :exit="{ opacity: 0, scale: 0.95, y: -10 }"
          :transition="{
            type: 'spring',
            stiffness: 300,
            damping: 30,
            mass: 0.8,
          }"
          class="fixed inset-0 z-50 flex items-start justify-center pt-20 sm:pt-24 px-3 sm:px-4"
          @click="closeDialog"
        >
          <motion.div
            @click.stop
            :initial="{ opacity: 0, scale: 0.8 }"
            :animate="{ opacity: 1, scale: 1 }"
            :exit="{ opacity: 0, scale: 0.9 }"
            :transition="{
              type: 'spring',
              stiffness: 400,
              damping: 25,
              delay: 0.1,
            }"
            class="bg-base-100 rounded-xl sm:rounded-2xl shadow-2xl border border-base-300 w-full max-w-4xl max-h-[85vh] sm:max-h-[90vh] overflow-hidden flex flex-col"
          >
            <!-- 标题栏 -->
            <div class="flex items-center justify-between p-4 sm:p-6 border-b border-base-300">
              <div class="flex items-center gap-2 sm:gap-3">
                <div class="text-xl sm:text-2xl">{{ currentCategoryInfo.icon }}</div>
                <div>
                  <h3 class="text-base sm:text-lg font-semibold text-base-content">主题选择器</h3>
                  <p class="text-xs sm:text-sm text-base-content/60 hidden sm:block">
                    {{ currentCategoryInfo.description }}
                  </p>
                </div>
              </div>
              <button @click="closeDialog" class="btn btn-ghost btn-xs sm:btn-sm btn-circle">
                <PhX class="w-3 h-3 sm:w-4 sm:h-4" />
              </button>
            </div>

            <!-- 分类选择器 -->
            <div class="p-3 sm:p-4 border-b border-base-300 bg-base-200/50">
              <div class="flex flex-wrap gap-1.5 sm:gap-2">
                <!-- 全部主题 -->
                <button
                  @click="selectCategory('all')"
                  class="category-btn btn btn-xs sm:btn-sm border-2 transition-all duration-200 text-xs sm:text-sm"
                  :class="{
                    'category-btn--active': selectedCategory === 'all',
                  }"
                  :style="{
                    backgroundColor: selectedCategory === 'all' ? '#6b7280' : 'transparent',
                    borderColor: '#6b7280',
                    color: selectedCategory === 'all' ? 'white' : '#6b7280',
                  }"
                >
                  🎨 全部
                </button>

                <!-- 分类按钮 -->
                <button
                  v-for="(category, index) in categories"
                  :key="category.id"
                  @click="selectCategory(category.id)"
                  class="category-btn btn btn-xs sm:btn-sm border-2 transition-all duration-200 text-xs sm:text-sm"
                  :class="{
                    'category-btn--active': selectedCategory === category.id,
                  }"
                  :style="{
                    animationDelay: `${(index + 1) * 0.1}s`,
                    backgroundColor:
                      selectedCategory === category.id ? category.color : 'transparent',
                    borderColor: category.color,
                    color: selectedCategory === category.id ? 'white' : category.color,
                  }"
                  :title="category.description"
                >
                  {{ category.icon }} {{ category.name }}
                </button>
              </div>
            </div>

            <!-- 主题列表 -->
            <div class="flex-1 overflow-y-auto p-3 sm:p-4 theme-switcher-scroll">
              <motion.div
                layout
                :transition="{ type: 'spring', stiffness: 300, damping: 30 }"
                class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4"
              >
                <motion.div
                  v-for="(theme, index) in filteredThemes"
                  :key="theme.id"
                  layout
                  :initial="{ opacity: 0, y: 20, scale: 0.9 }"
                  :animate="{
                    opacity: 1,
                    y: 0,
                    scale: 1,
                    transition: {
                      delay: index * 0.05,
                      type: 'spring',
                      stiffness: 400,
                      damping: 25,
                    },
                  }"
                  :exit="{ opacity: 0, y: -20, scale: 0.9 }"
                  :whileHover="{ scale: 1.02, y: -2 }"
                  :whileTap="{ scale: 0.98 }"
                  :transition="{ type: 'spring', stiffness: 400, damping: 25 }"
                  class="theme-item h-full"
                >
                  <div
                    @click="selectTheme(theme.id)"
                    class="theme-card group cursor-pointer bg-white rounded-xl border-2 transition-all duration-300 h-full flex flex-col hover:shadow-xl hover:-translate-y-1 relative overflow-hidden"
                    :class="{
                      'shadow-xl transform -translate-y-1': theme.id === currentTheme.id,
                      'shadow-lg': theme.id === previewTheme && theme.id !== currentTheme.id,
                    }"
                    :style="{
                      borderColor:
                        theme.id === currentTheme.id
                          ? theme.colors.primary
                          : theme.id === previewTheme
                            ? theme.colors.secondary
                            : '#e5e7eb',
                    }"
                  >
                    <!-- 渐变头部背景 -->
                    <div
                      class="absolute top-0 left-0 right-0 h-16 opacity-10"
                      :style="{
                        background: `linear-gradient(135deg, ${theme.colors.primary} 0%, ${theme.colors.secondary} 100%)`,
                      }"
                    ></div>

                    <!-- 主题预览 -->
                    <div class="relative flex flex-col h-full p-3">
                      <!-- 头部区域 -->
                      <div class="flex items-center justify-between mb-3">
                        <!-- 主题图标 -->
                        <div class="relative">
                          <div
                            class="w-12 h-12 rounded-xl flex items-center justify-center text-xl font-bold shadow-md relative overflow-hidden"
                            :style="{
                              background: `linear-gradient(135deg, ${theme.colors.primary} 0%, ${theme.colors.secondary} 100%)`,
                              color: 'white',
                            }"
                          >
                            {{ theme.icon }}

                            <!-- 光泽效果 -->
                            <div
                              class="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent"
                            ></div>
                          </div>

                          <!-- 状态指示器 -->
                          <div
                            v-if="theme.id === currentTheme.id"
                            class="absolute -top-1 -right-1 w-4 h-4 rounded-full flex items-center justify-center shadow-md"
                            :style="{ backgroundColor: '#10b981' }"
                          >
                            <PhCheck class="w-2.5 h-2.5 text-white" />
                          </div>

                          <div
                            v-else-if="theme.id === previewTheme"
                            class="absolute -top-1 -right-1 w-4 h-4 rounded-full flex items-center justify-center animate-pulse shadow-md"
                            :style="{ backgroundColor: theme.colors.accent }"
                          >
                            <PhEye class="w-2.5 h-2.5 text-white" />
                          </div>
                        </div>

                        <!-- 快速操作按钮 -->
                        <div class="flex gap-1.5">
                          <!-- 预览按钮 -->
                          <motion.button
                            @click.stop="selectTheme(theme.id)"
                            :whileHover="{ scale: 1.1 }"
                            :whileTap="{ scale: 0.9 }"
                            :transition="{ type: 'spring', stiffness: 400, damping: 25 }"
                            class="w-7 h-7 rounded-full flex items-center justify-center transition-all duration-200 shadow-sm"
                            :style="{
                              backgroundColor:
                                theme.id === previewTheme
                                  ? theme.colors.accent
                                  : 'rgba(255,255,255,0.9)',
                              color: theme.id === previewTheme ? 'white' : theme.colors.secondary,
                            }"
                            :title="theme.id === previewTheme ? '预览中' : '预览主题'"
                          >
                            <PhEye class="w-4 h-4" />
                          </motion.button>

                          <!-- 应用按钮 -->
                          <motion.button
                            @click.stop="applyTheme(theme.id)"
                            :whileHover="{ scale: 1.1 }"
                            :whileTap="{ scale: 0.9 }"
                            :transition="{ type: 'spring', stiffness: 400, damping: 25 }"
                            class="w-7 h-7 rounded-full flex items-center justify-center transition-all duration-200 shadow-sm"
                            :style="{
                              backgroundColor:
                                theme.id === currentTheme.id ? '#10b981' : theme.colors.primary,
                              color: 'white',
                            }"
                            :disabled="isTransitioning || theme.id === currentTheme.id"
                            :title="theme.id === currentTheme.id ? '已应用' : '应用主题'"
                          >
                            <span
                              v-if="isTransitioning && theme.id === previewTheme"
                              class="loading loading-spinner loading-xs"
                            ></span>
                            <PhCheck v-else-if="theme.id === currentTheme.id" class="w-4 h-4" />
                            <PhCheck v-else class="w-4 h-4" />
                          </motion.button>
                        </div>
                      </div>

                      <!-- 主题信息区域 -->
                      <div class="flex-1 flex flex-col space-y-2">
                        <!-- 主题名称和分类 -->
                        <div class="flex items-center justify-between gap-2">
                          <h3
                            class="text-base font-bold text-gray-800 leading-tight flex-1 truncate"
                          >
                            {{ theme.name }}
                          </h3>
                          <span
                            class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0"
                            :style="{
                              backgroundColor: `${theme.colors.primary}20`,
                              color: theme.colors.primary,
                            }"
                          >
                            {{
                              categories.find((c) => c.id === theme.category)?.name ||
                              theme.category
                            }}
                          </span>
                        </div>

                        <!-- 描述文本 -->
                        <div class="flex-1">
                          <p class="text-xs text-gray-600 leading-relaxed line-clamp-2">
                            {{ theme.description }}
                          </p>
                        </div>

                        <!-- 底部信息 -->
                        <div
                          class="flex items-center justify-between pt-1.5 border-t border-gray-100"
                        >
                          <!-- 颜色预览 -->
                          <div class="flex items-center gap-1.5">
                            <span class="text-xs text-gray-500 font-medium">颜色</span>
                            <div class="flex gap-1">
                              <div
                                class="w-4 h-4 rounded-full border-2 border-white shadow-sm"
                                :style="{
                                  backgroundColor: theme.colors.primary,
                                }"
                                :title="`主色: ${theme.colors.primary}`"
                              ></div>
                              <div
                                class="w-4 h-4 rounded-full border-2 border-white shadow-sm"
                                :style="{
                                  backgroundColor: theme.colors.secondary,
                                }"
                                :title="`次色: ${theme.colors.secondary}`"
                              ></div>
                              <div
                                class="w-4 h-4 rounded-full border-2 border-white shadow-sm"
                                :style="{
                                  backgroundColor: theme.colors.accent,
                                }"
                                :title="`强调色: ${theme.colors.accent}`"
                              ></div>
                            </div>
                          </div>

                          <!-- 状态标签 -->
                          <div
                            v-if="theme.id === currentTheme.id"
                            class="flex items-center gap-1 text-green-600"
                          >
                            <PhCheck class="w-4 h-4" />
                            <span class="text-xs font-medium">当前主题</span>
                          </div>
                          <div
                            v-else-if="theme.id === previewTheme"
                            class="flex items-center gap-1 text-blue-600"
                          >
                            <PhEye class="w-4 h-4" />
                            <span class="text-xs font-medium">预览中</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </motion.div>
              </motion.div>
            </div>

            <!-- 空状态 -->
            <motion.div
              v-if="filteredThemes.length === 0"
              :initial="{ opacity: 0, y: 20 }"
              :animate="{ opacity: 1, y: 0 }"
              :transition="{ type: 'spring', stiffness: 300, damping: 30 }"
              class="flex flex-col items-center justify-center py-12 text-center"
            >
              <div class="text-4xl mb-4">🎨</div>
              <h4 class="text-lg font-semibold text-base-content mb-2">暂无主题</h4>
              <p class="text-base-content/60">该分类下暂时没有可用的主题</p>
            </motion.div>
          </motion.div>
        </motion.div>
      </AnimatePresence>
    </Teleport>
  </div>
</template>

<style scoped>
/* 背景遮罩 */
.fixed.inset-0 {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(8px);
  animation: backdrop-fade-in 0.3s ease-out;
}

@keyframes backdrop-fade-in {
  from {
    background: rgba(0, 0, 0, 0);
    backdrop-filter: blur(0px);
  }
  to {
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(8px);
  }
}

/* 主题项动画 */
.theme-item {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  animation: theme-item-enter 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  min-height: 160px; /* 减少卡片最小高度 */
}

/* 主题卡片样式 */
.theme-card {
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.theme-card:hover {
  box-shadow:
    0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

@keyframes theme-item-enter {
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 主题选项样式 */
.theme-option {
  position: relative;
  overflow: hidden;
  transform-origin: center;
  transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.theme-option:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.theme-option:active {
  transform: translateY(0) scale(0.98);
  transition-duration: 0.1s;
}

.theme-option::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transition: left 0.5s;
}

.theme-option:hover::before {
  left: 100%;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 加载状态样式 */
.loading {
  pointer-events: none;
}

/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: hsl(var(--b2));
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: hsl(var(--bc) / 0.3);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: hsl(var(--bc) / 0.5);
}

/* 分类按钮动画 */
.category-btn {
  position: relative;
  overflow: hidden;
  opacity: 0;
  transform: translateY(10px) scale(0.9);
  animation: category-btn-enter 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes category-btn-enter {
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.category-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  z-index: 0;
}

.category-btn:hover::before {
  width: 200px;
  height: 200px;
}

.category-btn:hover {
  transform: translateY(-2px) scale(1.05);
}

.category-btn:active {
  transform: translateY(0) scale(0.95);
  transition-duration: 0.1s;
}

.category-btn--active {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.category-btn--active::after {
  content: '';
  position: absolute;
  inset: -2px;
  border: 2px solid currentColor;
  border-radius: inherit;
  opacity: 0.3;
  animation: pulse-border 2s infinite;
}

@keyframes pulse-border {
  0%,
  100% {
    opacity: 0.3;
    transform: scale(1);
  }
  50% {
    opacity: 0.1;
    transform: scale(1.05);
  }
}

/* 主题切换按钮动画 */
.theme-toggle-btn {
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  position: relative;
}

.theme-toggle-btn::before {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 50%;
  background: linear-gradient(135deg, hsl(var(--p)) 0%, hsl(var(--s)) 100%);
  opacity: 0;
  transform: scale(0.8);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  z-index: -1;
}

.theme-toggle-btn:hover::before {
  opacity: 0.1;
  transform: scale(1);
}

.theme-toggle-btn--active::before {
  opacity: 0.2;
  transform: scale(1.1);
  animation: active-pulse 2s infinite;
}

@keyframes active-pulse {
  0%,
  100% {
    opacity: 0.2;
    transform: scale(1.1);
  }
  50% {
    opacity: 0.1;
    transform: scale(1.2);
  }
}

.theme-icon {
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-origin: center;
}

.theme-toggle-btn:hover .theme-icon {
  transform: scale(1.2) rotate(10deg);
}

.theme-toggle-btn--active .theme-icon {
  transform: scale(1.1) rotate(180deg);
}

.theme-toggle-btn:active .theme-icon {
  transform: scale(0.9);
  transition-duration: 0.1s;
}

/* 加载状态样式 */
.loading .theme-icon {
  opacity: 0.5;
  animation: loading-bounce 1s infinite;
}

@keyframes loading-bounce {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

/* 预览状态样式 - 现在通过内联样式处理 */

/* 应用主题按钮样式 */
.apply-theme-btn:hover:not(:disabled) {
  background-color: var(--secondary-color) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.apply-theme-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

/* 底部操作区动画 */
.preview-actions {
  animation: slide-up 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 确定按钮样式 */
.btn-primary {
  position: relative;
  overflow: hidden;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.btn-primary:hover::before {
  width: 200px;
  height: 200px;
}

.btn-primary:active {
  transform: scale(0.95);
  transition-duration: 0.1s;
}

@keyframes slide-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 预览指示器动画 */
.preview-indicator {
  animation: preview-indicator-enter 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes preview-indicator-enter {
  from {
    opacity: 0;
    transform: scale(0.5) rotate(-90deg);
  }
  to {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }
}
</style>
